package com.ruoyi.analyse.manager;

import com.ruoyi.analyse.model.SafetyDto;
import com.ruoyi.analyse.model.FileDto;
import com.ruoyi.analyse.service.CollectParser;
import com.ruoyi.common.utils.SnowflakeIdUtils;
import com.ruoyi.safety.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
 * @author lth
 * @PackageName:com.ruoyi.common.collect.safety.service
 * @ClassName:SafetyParser
 * @Description:
 * @date 2024/10/30 11:09
 */
@Slf4j
public class SafetyParser extends CollectParser {
    public SafetyParser(SafetyDto safetyDto, final Charset charset) {
        mapper = safetyDto;
        this.charset = charset;
    }

    @Override
    public void parse(List<FileDto> files) {
        Stream.of((Consumer<List<FileDto>>)
                        this::analyzePointInfo,
                this::analyzeSafetyPointRealTime,
                this::analyzePointAbnormal,
                this::analyzeSafetyPointCount,
                this::analyzeSubstationInfo,
                this::analyzeSafetySubstationRealTime
        ).parallel().forEach(a -> tryAnalyze(a, files));
    }

    @Override
    protected String getFileNameRegex(final String type) {
        return String.join("", "(\\d+)_", type, "_(\\d{14}).txt");
    }

    protected String getDatum(String[] data, int index) {
        if (data == null || data.length <= index) {
            log.warn("null[{}]: {}", data, index);
            return null;
        }
        String datum = data[index];
        if (!StringUtils.hasText(datum)) {
            log.warn("empty[{}]: {}", data, index);
        }
        return datum.trim();
    }

    //测点异常数据信息
    protected void analyzePointAbnormal(List<FileDto> fileInfos) {
        analyze("YCBJ", fileInfos, this::analyzePointAbnormal);
        System.out.println("测点异常数据信息");
    }

    private void analyzePointAbnormal(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {

                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 16) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetyPointAbnormal safetyPointAbnormal = new SafetyPointAbnormal();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    safetyPointAbnormal.setPointCode(getDatum(data, 0));
                    safetyPointAbnormal.setSensorTypeName(getDatum(data, 1));
                    safetyPointAbnormal.setPointInstallLocation(getDatum(data, 2));

                    //单位  值为模拟量必填  需要根据  code查询对象  取值进行判断
                    SafetyPointInfo safetyPointInfo = mapper.getSafetyPointInfoService().selectSafetyPointInfoByPointCode(getDatum(data, 0));
                    if (Objects.nonNull(safetyPointInfo)) {
                        if ("MN".equals(safetyPointInfo.getPointValueType())) {
                            safetyPointAbnormal.setPointValueUnit(getDatum(data, 3));
                            safetyPointAbnormal.setAbnormalMaxValue(getDatum(data, 7));
                            safetyPointAbnormal.setMaxValueTime(dateFormat.parse(getDatum(data, 8)));
                            safetyPointAbnormal.setAbnormalMinValue(getDatum(data, 9));
                            safetyPointAbnormal.setMinValueTime(dateFormat.parse(getDatum(data, 10)));
                            safetyPointAbnormal.setAbnormalAverageValue(getDatum(data, 11));

                        }
                    }

                    PointTypeDict pointTypeDict = mapper.getPointTypeDictService().selectPointTypeDictByCode(getDatum(data, 4));
                    if (Objects.nonNull(pointTypeDict)) {
                        safetyPointAbnormal.setAbnormalType(pointTypeDict.getDesc());
                    }
                    //获取时间字符串，转date保存
                    safetyPointAbnormal.setAbnormalBeginTime(dateFormat.parse(getDatum(data, 5)));

                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 6))) {
                        safetyPointAbnormal.setAbnormalEndTime(dateFormat.parse(getDatum(data, 6)));
                    }
                    safetyPointAbnormal.setAbnormalReason(getDatum(data, 12));
                    safetyPointAbnormal.setHandMeasure(getDatum(data, 13));
                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 14))) {
                        safetyPointAbnormal.setUploadTime(dateFormat.parse(getDatum(data, 14)));
                    }
                    safetyPointAbnormal.setUploadPerson(getDatum(data, 15));
                    safetyPointAbnormal.setCreateTime(dateFormat.parse(getDatum(data, 16)));

                    SafetyPointAbnormal pointAbnormal = mapper.getSafetyPointAbnormalService().selectSafetyPointAbnormalByPointCode(safetyPointAbnormal.getPointCode());
                    if (Objects.nonNull(pointAbnormal)) {
                        mapper.getSafetyPointAbnormalService().updateSafetyPointAbnormal(safetyPointAbnormal);
                    } else {
                        mapper.getSafetyPointAbnormalService().insertSafetyPointAbnormal(safetyPointAbnormal);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //测点基本信息
    protected void analyzePointInfo(List<FileDto> fileInfos) {
        analyze("CDDY", fileInfos, this::analyzePointInfo);
        System.out.println("测点基本信息");
    }

    private void analyzePointInfo(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 23) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetyPointInfo safetyPointInfo = new SafetyPointInfo();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


                    safetyPointInfo.setPointCode(getDatum(data, 0));

                    SystemCodeDict systemCode = mapper.getSystemCodeDictService().selectSystemCodeDictBySystemCode(getDatum(data, 1));
                    if (Objects.nonNull(systemCode)) {
                        safetyPointInfo.setSystemCode(systemCode.getDesc());
                    }
                    safetyPointInfo.setSubstationCode(getDatum(data, 2));
                    SensorTypeDict sensorTypeDict = mapper.getSensorTypeDictService().selectSensorTypeDictByCode(getDatum(data, 3));
                    if (Objects.nonNull(sensorTypeDict)) {
                        safetyPointInfo.setSensorType(sensorTypeDict.getDesc());
                    }

                    PointValueDict pointValueDict = mapper.getPointValueDictService().selectPointValueDictByPointCode(getDatum(data, 4));
                    if (Objects.nonNull(pointValueDict)) {
                        safetyPointInfo.setPointValueType(pointValueDict.getDesc());
                    }


                    //测点数值类型为  MN  必填
                    if ("MN".equals(getDatum(data, 4))) {
                        safetyPointInfo.setPointValueUnit(getDatum(data, 5));
//                        PointUitDict pointUitDict = mapper.getPointUitDictService().selectPointUitDictByCode(getDatum(data, 5));
//                        if (Objects.nonNull(pointUitDict)) {
//                            safetyPointInfo.setPointValueUnit(pointValueDict.getDesc());
//                        }
                        safetyPointInfo.setHighRange(getDatum(data, 6));
                        safetyPointInfo.setLowRange(getDatum(data, 7));
                        safetyPointInfo.setUpperAlarmLimit(getDatum(data, 8));
                        safetyPointInfo.setUpperRemoveLimit(getDatum(data, 9));
                        safetyPointInfo.setLowerAlarmLimit(getDatum(data, 10));
                        safetyPointInfo.setLowerRemoveLimit(getDatum(data, 11));
                        safetyPointInfo.setUpperInterruptLimit(getDatum(data, 12));
                        safetyPointInfo.setUpperReplyLimit(getDatum(data, 13));
                        safetyPointInfo.setLowerInterruptLimit(getDatum(data, 14));
                        safetyPointInfo.setLowerReplyLimit(getDatum(data, 15));
                    }

                    //测点类型  KG  必填
                    if ("KG".equals(getDatum(data, 4))) {
                        safetyPointInfo.setOpenDescription(getDatum(data, 16));
                        safetyPointInfo.setCloseDescription(getDatum(data, 17));
//                        //查实时信息  测点值   1  必填
//                        if ("1".equals(getDatum(data, 16))) {
//                            safetyPointInfo.setOpenDescription("有烟雾");
//                        }
//                        // 0   必填
//                        if ("0".equals(getDatum(data, 17))) {
//                            safetyPointInfo.setCloseDescription("无烟雾");
//                        }
                    }

                    safetyPointInfo.setEquipmentMonitorLocation(getDatum(data, 18));
                    safetyPointInfo.setCoorX(getDatum(data, 19));
                    safetyPointInfo.setCoorY(getDatum(data, 20));
                    safetyPointInfo.setCoorZ(getDatum(data, 21));

//                    PointRelationshipDict pointRelationshipDict = mapper.getPointRelationshipDictService().selectPointRelationshipDictByCode(getDatum(data, 22));
//                    if (Objects.nonNull(pointRelationshipDict)){
//                        safetyPointInfo.setSensorRelationship(pointRelationshipDict.getDesc());
//                    }
                    safetyPointInfo.setSensorRelationship(getDatum(data, 22));
                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 23))) {
                        safetyPointInfo.setUploadTime(dateFormat.parse(getDatum(data, 23)));
                    }

                    SafetyPointInfo pointInfo = mapper.getSafetyPointInfoService().selectSafetyPointInfoByPointCode(safetyPointInfo.getPointCode());
                    if (Objects.nonNull(pointInfo)) {
                        mapper.getSafetyPointInfoService().updateSafetyPointInfo(safetyPointInfo);

                        String pointCode = safetyPointInfo.getPointCode();

                    } else {
                        mapper.getSafetyPointInfoService().insertSafetyPointInfo(safetyPointInfo);

//                        Device device = new Device();
//                        device.setDeviceId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
//                        //测点、分站code
//                        device.setRedlineId(safetyPointInfo.getPointCode());
//                        device.setCameraStatus(safetyPointInfo.getSubstationCode());
//                        device.setInstallAdress(safetyPointInfo.getEquipmentMonitorLocation());
//                        //传感器类型
//                        device.setDeviceFunction(safetyPointInfo.getSensorType());
//
//                        mapper.getDeviceService().insertDevice(device);
                    }


                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }


    //分站基本信息
    protected void analyzeSubstationInfo(List<FileDto> fileInfos) {
        analyze("FZDY", fileInfos, this::analyzeSubstationInfo);
        System.out.println("分站基本信息");
    }

    private void analyzeSubstationInfo(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");

                    // 检查第二个部分的字段数量
                    if (data.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetySubstationInfo safetySubstationInfo = new SafetySubstationInfo();

                    safetySubstationInfo.setSubstationCode(getDatum(data, 0));
                    safetySubstationInfo.setSubstationInstallLocation(getDatum(data, 1));
                    safetySubstationInfo.setCoorX(getDatum(data, 2));
                    safetySubstationInfo.setCoorY(getDatum(data, 3));
                    safetySubstationInfo.setCoorZ(getDatum(data, 4));

                    SafetySubstationInfo substationInfo = mapper.getSubstationInfoService().selectSafetySubstationInfoBySubstationCode(safetySubstationInfo.getSubstationCode());
                    if (Objects.nonNull(substationInfo)) {
                        mapper.getSubstationInfoService().updateSafetySubstationInfo(safetySubstationInfo);
                    } else {
                        mapper.getSubstationInfoService().insertSafetySubstationInfo(safetySubstationInfo);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //测点实时信息数据
    protected void analyzeSafetyPointRealTime(List<FileDto> fileInfos) {
        analyze("CDSS", fileInfos, this::analyzeSafetyPointRealTime);
        System.out.println("测点实时信息数据");
    }
//
//    private void analyzeSafetyPointRealTime(List<String> matches, String content, FileDto fileInfo) {
//        long begin = System.currentTimeMillis();
//        int count = 0;
//        String[] lines = content.split("\\|\\|");
//
//        for (String line : lines) {
//            try {
//                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
//
//                if (parts.length < 2) {
//                    // 如果字段数量不足，跳过该行
//                    log.warn("Invalid line: {}", line);
//                    continue;
//                }
//                for (int i = 1; i < parts.length; i++) {
//                    // 第二个部分使用 ';' 分割
//                    String[] data = parts[i].split(";");
//                    // 检查第二个部分的字段数量
//                    if (data.length < 6) {
//                        // 如果字段数量不足，跳过该行
//                        log.warn("Invalid data: {}", line);
//                        continue;
//                    }
//                    long start = System.currentTimeMillis();
//
//                    SafetyPointRealTime safetyPointRealTime = new SafetyPointRealTime();
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//                    safetyPointRealTime.setPointCode(getDatum(data, 0));
//                    safetyPointRealTime.setSensorTypeName(getDatum(data, 1));
//                    safetyPointRealTime.setPointInstallLocation(getDatum(data, 2));
//
////                    //测点类型  MN  测点实际值   KG  0/1   多态  实际值
////                    SafetyPointInfo safetyPointInfo = mapper.getSafetyPointInfoService().selectSafetyPointInfoByPointCode(getDatum(data, 0));
////                    if (Objects.nonNull(safetyPointInfo)) {
////                        //测点数值类型
////                        String pointValueType = safetyPointInfo.getPointValueType();
////                        if ("MN".equals(pointValueType)) {
////                            //测点值
////                            safetyPointRealTime.setPointValue(getDatum(data, 3));
////                            //测点数值单位
////                            safetyPointRealTime.setPointValueUnit(getDatum(data, 4));
////                        }
////                        if ("KG".equals(pointValueType)) {
////                            safetyPointRealTime.setPointValue(getDatum(data, 3));
////                        }
////                        if ("DT".equals(pointValueType)) {
////                            safetyPointRealTime.setPointValue(getDatum(data, 3));
////                        }
////                    }
//                    safetyPointRealTime.setPointValue(getDatum(data, 3));
//                    safetyPointRealTime.setPointValueUnit(getDatum(data, 4));
//
//                    //十进制字符串 数字  转  8位 二进制字符串
//                    String decimalString = getDatum(data, 5);
//                    int decimalNumber = Integer.parseInt(decimalString);
//                    String binaryString = String.format("%8s", Integer.toBinaryString(decimalNumber)).replace(' ', '0');
//
//                    PointStatusDict pointStatusDict = mapper.getPointStatusDictService().selectPointStatusDictByNum(binaryString);
//                    if (Objects.nonNull(pointStatusDict)) {
//                        safetyPointRealTime.setPointStatus(pointStatusDict.getDesc());
//                    }
////                    safetyPointRealTime.setPointStatus(getDatum(data, 5));
//
//                    safetyPointRealTime.setUploadTime(dateFormat.parse(getDatum(data, 6)));
//
//                    SafetyPointRealTime pointRealTime = mapper.getSafetyPointRealTimeService().selectSafetyPointRealTimeByPointCode(getDatum(data, 0));
//
////                    SafetyPointRealHistory safetyPointRealHistory = new SafetyPointRealHistory();
////                    long id = new SnowflakeIdUtils(5, 8).nextId();
////                    safetyPointRealHistory.setId(String.valueOf(id));
////                    BeanUtils.copyProperties(pointRealTime,safetyPointRealHistory);
////                    mapper.getSafetyPointRealHistoryService().insertSafetyPointRealHistory(safetyPointRealHistory);
//
//
//                    if (Objects.nonNull(pointRealTime)) {
//                        SafetyPointRealHistory safetyPointRealHistory = new SafetyPointRealHistory();
//                        long id = new SnowflakeIdUtils(5, 8).nextId();
//                        safetyPointRealHistory.setId(String.valueOf(id));
//                        BeanUtils.copyProperties(pointRealTime,safetyPointRealHistory);
//                        mapper.getSafetyPointRealHistoryService().insertSafetyPointRealHistory(safetyPointRealHistory);
//
//
//                        mapper.getSafetyPointRealTimeService().updateSafetyPointRealTime(safetyPointRealTime);
//                    } else {
//                        mapper.getSafetyPointRealTimeService().insertSafetyPointRealTime(safetyPointRealTime);
//                    }
//
//                    log.info("cost:" + (System.currentTimeMillis() - start));
//
//                    count++;
//                }
//            } catch (Exception e) {
//                log.warn("", e);
//                log.warn("analyze_fail:[{}]", line);
//            }
//        }
//
//        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
//        fileInfo.setAnalyzed(true);
//    }

    private void analyzeSafetyPointRealTime(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        List<SafetyPointRealHistory> safetyPointRealHistoryArrayList = new ArrayList<SafetyPointRealHistory>();
        List<SafetyPointRealTime> pointInfoRealTimeArrayList = new ArrayList<>();
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 6) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetyPointRealTime safetyPointRealTime = new SafetyPointRealTime();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


                    safetyPointRealTime.setPointCode(getDatum(data, 0));

                    safetyPointRealTime.setSensorTypeName(getDatum(data, 1));
                    safetyPointRealTime.setPointInstallLocation(getDatum(data, 2));

                    safetyPointRealTime.setPointValue(getDatum(data, 3));
                    safetyPointRealTime.setPointValueUnit(getDatum(data, 4));

                    //十进制字符串 数字  转  8位 二进制字符串
                    String decimalString = getDatum(data, 5);
                    int decimalNumber = Integer.parseInt(decimalString);
                    String binaryString = String.format("%8s", Integer.toBinaryString(decimalNumber)).replace(' ', '0');

                    PointStatusDict pointStatusDict = mapper.getPointStatusDictService().selectPointStatusDictByNum(binaryString);
                    if (Objects.nonNull(pointStatusDict)) {
                        safetyPointRealTime.setPointStatus(pointStatusDict.getDesc());
                    }
//                    safetyPointRealTime.setPointStatus(getDatum(data, 5));

//                    safetyPointRealTime.setUploadTime(dateFormat.parse(getDatum(data, 6)));
                    safetyPointRealTime.setUpdateTime(dateFormat.parse(getDatum(data, 6)));


                    SafetyPointRealTime pointRealTime = mapper.getSafetyPointRealTimeService().selectSafetyPointRealTimeByPointCode(getDatum(data, 0));


                    if (Objects.nonNull(pointRealTime)) {

                        SafetyPointRealHistory safetyPointRealHistory = new SafetyPointRealHistory();
                        long id = new SnowflakeIdUtils(5, 8).nextId();
                        safetyPointRealHistory.setId(String.valueOf(id));
                        BeanUtils.copyProperties(pointRealTime, safetyPointRealHistory);

                        safetyPointRealHistoryArrayList.add(safetyPointRealHistory);
                        if (safetyPointRealHistoryArrayList.size() > 99) {
                            mapper.getSafetyPointRealHistoryService().insertDataBatch(safetyPointRealHistoryArrayList);
                            safetyPointRealHistoryArrayList.clear();
                        }

                        pointInfoRealTimeArrayList.add(safetyPointRealTime);

                        if (pointInfoRealTimeArrayList.size() > 99) {
                            mapper.getSafetyPointRealTimeService().updateDataBatch(pointInfoRealTimeArrayList);
                            pointInfoRealTimeArrayList.clear();
                        }
//                        mapper.getSafetyPointRealTimeService().updateSafetyPointRealTime(safetyPointRealTime);
                    } else {
//                        pointInfoRealTimeArrayList.add(safetyPointRealTime);
                        mapper.getSafetyPointRealTimeService().insertSafetyPointRealTime(safetyPointRealTime);
//                        if (pointInfoRealTimeArrayList.size() > 99) {
//                            mapper.getSafetyPointRealTimeService().insertRealTimeBatch(pointInfoRealTimeArrayList);
//                            pointInfoRealTimeArrayList.clear();
//                        }
                    }

                    if (!safetyPointRealHistoryArrayList.isEmpty()) {
                        mapper.getSafetyPointRealHistoryService().insertDataBatch(safetyPointRealHistoryArrayList);
                        safetyPointRealHistoryArrayList.clear(); // 清空列表，但通常在此之后不需要再使用它，所以这一步可能是可选的
                    }

                    if (!pointInfoRealTimeArrayList.isEmpty()) {
                        mapper.getSafetyPointRealTimeService().updateDataBatch(pointInfoRealTimeArrayList);
                        pointInfoRealTimeArrayList.clear(); // 同样，这一步可能是可选的
                    }
                    mapper.getGradedAlarmService().handleAlarmNormal(getDatum(data, 2),getDatum(data, 1),getDatum(data, 3));

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }


    //测点统计信息数据
    protected void analyzeSafetyPointCount(List<FileDto> fileInfos) {
        analyze("TJSJ", fileInfos, this::analyzeSafetyPointCount);
        System.out.println("测点统计信息数据");
    }


    private void analyzeSafetyPointCount(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 11) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetyPointCount safetyPointCount = new SafetyPointCount();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    safetyPointCount.setPointCode(getDatum(data, 0));
                    safetyPointCount.setSensorTypeName(getDatum(data, 1));
                    safetyPointCount.setPointInstallLocation(getDatum(data, 2));
                    safetyPointCount.setPointValueUnit(getDatum(data, 3));
                    safetyPointCount.setBeginTime(dateFormat.parse(getDatum(data, 4)));
                    safetyPointCount.setEndTime(dateFormat.parse(getDatum(data, 5)));
                    safetyPointCount.setMaxValue(getDatum(data, 6));
                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 7))) {
                        safetyPointCount.setMaxValueTime(dateFormat.parse(getDatum(data, 7)));
                    }

                    safetyPointCount.setMinValue(getDatum(data, 8));
                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 9))) {
                        safetyPointCount.setMinValueTime(dateFormat.parse(getDatum(data, 9)));
                    }

                    safetyPointCount.setAverageValue(getDatum(data, 10));

                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 11))) {
                        safetyPointCount.setUploadTime(dateFormat.parse(getDatum(data, 11)));
                    }

                    SafetyPointCount pointCount = mapper.getSafetyPointCountService().selectSafetyPointCountByPointCode(getDatum(data, 0));
                    if (Objects.nonNull(pointCount)) {
                        mapper.getSafetyPointCountService().updateSafetyPointCount(safetyPointCount);
                    } else {
                        mapper.getSafetyPointCountService().insertSafetyPointCount(safetyPointCount);
                    }

                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    //分站实时信息数据
    protected void analyzeSafetySubstationRealTime(List<FileDto> fileInfos) {
        analyze("FZSS", fileInfos, this::analyzeSafetySubstationRealTime);
        System.out.println("分站实时信息数据");
    }

//    private void analyzeSafetySubstationRealTime(List<String> matches, String content, FileDto fileInfo) {
//        long begin = System.currentTimeMillis();
//        int count = 0;
//        String[] lines = content.split("\\|\\|");
//
//        for (String line : lines) {
//            try {
//                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
//
//                if (parts.length < 2) {
//                    // 如果字段数量不足，跳过该行
//                    log.warn("Invalid line: {}", line);
//                    continue;
//                }
//                for (int i = 1; i < parts.length; i++) {
//                    // 第二个部分使用 ';' 分割
//                    String[] data = parts[i].split(";");
//                    // 检查第二个部分的字段数量
//                    if (data.length < 3) {
//                        // 如果字段数量不足，跳过该行
//                        log.warn("Invalid data: {}", line);
//                        continue;
//                    }
//                    long start = System.currentTimeMillis();
//
//                    SafetySubstationRealTime safetySubstationRealTime = new SafetySubstationRealTime();
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//                    safetySubstationRealTime.setSubstationCode(getDatum(data, 0));
//
//                    SubstationStatusDict substationStatusDict = mapper.getSubstationStatusDictService().selectSubstationStatusDictByCode(getDatum(data, 1));
//                    if (Objects.nonNull(substationStatusDict)) {
//                        safetySubstationRealTime.setSubstationRunStatus(substationStatusDict.getDesc());
//                    }
//                    ElectricStatusDict electricStatusDict = mapper.getElectricStatusDictService().selectElectricStatusDictByCode(getDatum(data, 2));
//                    if (Objects.nonNull(electricStatusDict)) {
//                        safetySubstationRealTime.setSubstationElectricStatus(electricStatusDict.getDesc());
//                    }
//                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 3))) {
//                        safetySubstationRealTime.setUploadTime(dateFormat.parse(getDatum(data, 3)));
//                    }
//
////                    SafetySubstationRealTime substation = mapper.getSafetySubstationRealTimeService().selectSafetySubstationRealTimeBySubstationCode(getDatum(data, 0));
//
//
//                    SafetySubstationRealTime substation = mapper.getSafetySubstationRealTimeService().selectSafetySubstationRealTimeBySubstationCode(getDatum(data, 0));
//
////                    SafetySubstationHistory safetySubstationHistory = new SafetySubstationHistory();
////                    long id = new SnowflakeIdUtils(5, 8).nextId();
////                    safetySubstationHistory.setId(String.valueOf(id));
////                    BeanUtils.copyProperties(substation,safetySubstationHistory);
////                    mapper.getSafetySubstationHistoryService().insertSafetySubstationHistory(safetySubstationHistory);
//
//                    if (substation != null) {
//                        String substationRunStatus = substation.getSubstationRunStatus();
//                        String substationElectricStatus = substation.getSubstationElectricStatus();
//
////                        if (Objects.nonNull(substationRunStatus)){
////                            if ("0".equals(substationRunStatus)) {
////                                substation.setSubstationRunStatus("通讯正常");
////                            } else if ("1".equals(substationRunStatus)) {
////                                substation.setSubstationRunStatus("通讯中断");
////                            } else if ("2".equals(substationRunStatus)) {
////                                substation.setSubstationRunStatus("故障");
////                            } else if ("9".equals(substationRunStatus)) {
////                                substation.setSubstationRunStatus("未知");
////                            } else {
////                                substation.setSubstationRunStatus("未知状态");
////                            }
////                        }
////
////                        if (Objects.nonNull(substationElectricStatus)){
////                            if ("0".equals(substationElectricStatus)) {
////                                substation.setSubstationElectricStatus("直流供电");
////                            } else if ("1".equals(substationElectricStatus)) {
////                                substation.setSubstationElectricStatus("交流供电");
////                            } else if ("2".equals(substationElectricStatus)) {
////                                substation.setSubstationElectricStatus("电源故障");
////                            } else if ("9".equals(substationElectricStatus)) {
////                                substation.setSubstationElectricStatus("未知");
////                            } else {
////                                substation.setSubstationElectricStatus("未知状态");
////                            }
////                        }
//                        SafetySubstationHistory safetySubstationHistory = new SafetySubstationHistory();
//                        long id = new SnowflakeIdUtils(5, 8).nextId();
//                        safetySubstationHistory.setId(String.valueOf(id));
//                        BeanUtils.copyProperties(substation, safetySubstationHistory);
//                        mapper.getSafetySubstationHistoryService().insertSafetySubstationHistory(safetySubstationHistory);
//
//
//                        mapper.getSafetySubstationRealTimeService().updateSafetySubstationRealTime(safetySubstationRealTime);
//                    } else {
//                        mapper.getSafetySubstationRealTimeService().insertSafetySubstationRealTime(safetySubstationRealTime);
//                    }
//
//                    log.info("cost:" + (System.currentTimeMillis() - start));
//
//                    count++;
//                }
//            } catch (Exception e) {
//                log.warn("", e);
//                log.warn("analyze_fail:[{}]", line);
//            }
//        }
//
//        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
//        fileInfo.setAnalyzed(true);
//    }

    private void analyzeSafetySubstationRealTime(List<String> matches, String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

        ArrayList<SafetySubstationRealTime> substationRealTimeArrayList = new ArrayList<>();
        ArrayList<SafetySubstationHistory> substationHistoryArrayList = new ArrayList<>();
        for (String line : lines) {
            try {
                String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                if (parts.length < 2) {
                    // 如果字段数量不足，跳过该行
                    log.warn("Invalid line: {}", line);
                    continue;
                }
                for (int i = 1; i < parts.length; i++) {
                    // 第二个部分使用 ';' 分割
                    String[] data = parts[i].split(";");
                    // 检查第二个部分的字段数量
                    if (data.length < 3) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid data: {}", line);
                        continue;
                    }
                    long start = System.currentTimeMillis();

                    SafetySubstationRealTime safetySubstationRealTime = new SafetySubstationRealTime();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    safetySubstationRealTime.setSubstationCode(getDatum(data, 0));

                    SubstationStatusDict substationStatusDict = mapper.getSubstationStatusDictService().selectSubstationStatusDictByCode(getDatum(data, 1));
                    if (Objects.nonNull(substationStatusDict)) {
                        safetySubstationRealTime.setSubstationRunStatus(substationStatusDict.getDesc());
                    }
                    ElectricStatusDict electricStatusDict = mapper.getElectricStatusDictService().selectElectricStatusDictByCode(getDatum(data, 2));
                    if (Objects.nonNull(electricStatusDict)) {
                        safetySubstationRealTime.setSubstationElectricStatus(electricStatusDict.getDesc());
                    }
                    if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(getDatum(data, 3))) {
                        safetySubstationRealTime.setUploadTime(dateFormat.parse(getDatum(data, 3)));
                    }

//                    SafetySubstationRealTime substation = mapper.getSafetySubstationRealTimeService().selectSafetySubstationRealTimeBySubstationCode(getDatum(data, 0));


                    SafetySubstationRealTime substation = mapper.getSafetySubstationRealTimeService().selectSafetySubstationRealTimeBySubstationCode(getDatum(data, 0));


                    if (substation != null) {
                        String substationRunStatus = substation.getSubstationRunStatus();
                        String substationElectricStatus = substation.getSubstationElectricStatus();


                        SafetySubstationHistory safetySubstationHistory = new SafetySubstationHistory();
                        long id = new SnowflakeIdUtils(5, 8).nextId();
                        safetySubstationHistory.setId(String.valueOf(id));
                        BeanUtils.copyProperties(substation, safetySubstationHistory);

                        substationHistoryArrayList.add(safetySubstationHistory);
                        if (substationHistoryArrayList.size() > 99) {
                            mapper.getSafetySubstationHistoryService().insertDataBatch(substationHistoryArrayList);
                            substationHistoryArrayList.clear();
                        }

                        substationRealTimeArrayList.add(substation);
                        if (substationRealTimeArrayList.size() > 99) {
                            mapper.getSafetySubstationRealTimeService().updateDataBatch(substationRealTimeArrayList);
                            substationRealTimeArrayList.clear();
                        }

                    } else {
                        mapper.getSafetySubstationRealTimeService().insertSafetySubstationRealTime(safetySubstationRealTime);
                    }

                    if (!substationHistoryArrayList.isEmpty()) {
                        mapper.getSafetySubstationHistoryService().insertDataBatch(substationHistoryArrayList);
                        substationHistoryArrayList.clear(); // 清空列表，但通常在此之后不需要再使用它，所以这一步可能是可选的
                    }

                    if (!substationRealTimeArrayList.isEmpty()) {
                        mapper.getSafetySubstationRealTimeService().updateDataBatch(substationRealTimeArrayList);
                        substationRealTimeArrayList.clear(); // 同样，这一步可能是可选的
                    }


                    log.info("cost:" + (System.currentTimeMillis() - start));

                    count++;
                }
            } catch (Exception e) {
                log.warn("", e);
                log.warn("analyze_fail:[{}]", line);
            }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

}
